package com.topscomm.app.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.app.service.ITopscommPwdService;
import com.topscomm.basic.exception.BusinessException;
import com.topscomm.basic.util.Config;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboModuleEntity;
import com.topscomm.cbo.pojo.CboPermissionModuleEntity;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.cbo.service.ICboModuleService;
import com.topscomm.cbo.service.ICboPermissionModuleService;
import com.topscomm.cbo.service.ICboRoleService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.TokenUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.security.controller.AuthenticationController;
import com.topscomm.security.model.AuthenticationToken;
import com.topscomm.security.model.AuthorizationUser;
import com.topscomm.security.properties.LoginProperties;

import oracle.net.aso.e;
import oracle.net.aso.f;

/**
 * @ClassName: AppLoginController
 * @author: litianxing
 * @date: 2020年4月13日 下午5:39:53
 * @Description: APP相关
 */
@RestController
@RequestMapping("app")
public class AppLoginController extends AuthenticationController {
	@Autowired
	@Qualifier("securityUserDetailsService")
	private UserDetailsService userDetailsService;
	@Autowired
	private ICboUserService cboUserService;
	@Autowired
	private ICboRoleService cboRoleService;
	@Autowired
	private ICboDeptService cboDeptService;
	@Autowired
	private ICboModuleService cboModuleService;
	@Autowired
	private ICboPermissionModuleService cboPermissionModuleService;
	@Autowired
	private LoginProperties loginProperties;

	final static public String LOGIN_TYPE = "loginType";
	final static public String MOBILE = "mobile";

	/**
	 * @Title: appLogin
	 * @author: litianxing
	 * @param authorizationUser
	 * @return 登录结果
	 * @throws Exception
	 * @return_type: ResponseResult<Object>
	 * @Description: 登录接口，返回值包括角色列表、模块权限列表以及token
	 */
	@PostMapping(value = "/appLogin")
	public ResponseResult<Object> appLogin(@Validated @RequestBody AuthorizationUser authorizationUser)
			throws Exception {
		// 手机端登录标识
		externalData = new HashMap<String, Object>();
		externalData.put(LOGIN_TYPE, MOBILE);
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendLineSingle(" loginname = '{0}' ", authorizationUser.getUsername());
		List<CboUserEntity> users = cboUserService.queryByWhere(sql.toString());
		if (users == null || users.size() <= 0) {
			return ResponseResult.error("用户不存在");
		}
		try {
			ResponseResult<Object> responseResult = null;
			if (loginProperties.getTokenCreateType().equals("local")) {
				responseResult = localLogin(authorizationUser);
			} else if (loginProperties.getTokenCreateType().equals("oauth2")) {
				responseResult = oauth2Login(authorizationUser);
			} else {
				return ResponseResult.error("无效的Token生成类型");
			}
			if (responseResult != null) {
				AuthenticationToken authenticationToken = (AuthenticationToken) responseResult.getResult();
				Map<String, Object> dataMap = getRoleAndModuleOfUser(users.get(0));
				dataMap.put("authenticationToken", authenticationToken);
				return ResponseResult.ok(dataMap);
			} else {
				return ResponseResult.error("登录失败");
			}
		} catch (Exception ex) {  
			ex.printStackTrace();
			return ResponseResult.error(ex.getMessage());
		}
	}

	/**
	 * @Title: getRoleAndModuleOfUser
	 * @author: litianxing
	 * @param user
	 * @return
	 * @return_type: Map<String,Object>
	 * @Description: 获取登录人的权限列表与角色列表
	 */
	private Map<String, Object> getRoleAndModuleOfUser(CboUserEntity user) {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		// 查询角色
		List<CboRoleEntity> roles = cboRoleService.queryRolesByUserId(user.getId());
		// 加载菜单
		List<CboModuleEntity> listModule = new ArrayList<CboModuleEntity>();
		String rootCode = Config.getInstance().getValue("ModuleRootCode", "") + ","
				+ Config.getInstance().getValue("MobileModuleRootCode", "");
		if (user.getAdminlevel() != 9) {
			// 所在的所有部门列表
			CboDeptEntity dept = cboDeptService.queryById("" + user.getDeptid());
			// 查询部门以及上级部门
			String deptids_user = "";
			List<CboDeptEntity> list = cboDeptService.queryByWhere("enabled=1");
			for (CboDeptEntity ent : list) {
				if (ConvertUtil.convertToString(dept.getCode()).startsWith(ent.getCode())
						&& dept.getOrgid() == ent.getOrgid())
					deptids_user += "," + ent.getId();
			}
			if (deptids_user.startsWith(",")) {
				deptids_user = deptids_user.substring(1);
			}
			// 权限菜单
			List<CboPermissionModuleEntity> permissions = cboPermissionModuleService.queryUserModules(user.getId(),
					roles, deptids_user);
			List<String> listModuleId = new ArrayList<String>();
			for (int i = 0; permissions != null && i < permissions.size(); i++) {
				CboPermissionModuleEntity per = permissions.get(i);
				if (!listModuleId.contains(ConvertUtil.convertToString(per.getModuleid()))) {
					listModuleId.add(String.valueOf(per.getModuleid()));
				}
			}
			// 最终显示菜单
			listModule = cboModuleService.queryModule(listModuleId, rootCode);
		} else {// 管理员
			String[] codes = rootCode.split(",");
			String whereSql = "(";
			for (String code : codes) {
				whereSql += "code like '" + code + "%' or ";
			}
			whereSql = whereSql.substring(0, whereSql.length() - 3) + ")";
			listModule = cboModuleService.queryByWhere(whereSql + " and Enabled=1 order by sortcode,code asc ");
		}
		dataMap.put("roleList", filterRoleList(roles));
		dataMap.put("moduleList", filterModuleList(listModule));
		return dataMap;
	}

	/**
	 * @Title: filterModuleList
	 * @author: litianxing
	 * @param listModule
	 * @return
	 * @return_type: List<Map<String,Object>>
	 * @Description: 过滤手机端权限模块
	 */
	private List<Map<String, Object>> filterModuleList(List<CboModuleEntity> listModule) {
		List<Map<String, Object>> result = new ArrayList<>();
		for (CboModuleEntity cboModuleEntity : listModule) {
			// 扩展字段1为手机端编码，扩展字段2为手机端模块名称
			if (cboModuleEntity.getExtendfield1() != null) {
				Map<String, Object> module = new HashMap<>();
				if (cboModuleEntity.getExtendfield2() != null && !"".equals(cboModuleEntity.getExtendfield2())) {
					module.put("mobileName", cboModuleEntity.getExtendfield2());
				} else {
					module.put("mobileName", cboModuleEntity.getName());
				}
				module.put("mobileCode", cboModuleEntity.getExtendfield1());
				result.add(module);
			}
		}
		return result;
	}

	/**
	 * @Title: filterRoleList
	 * @author: litianxing
	 * @param roleList
	 * @return
	 * @return_type: List<Map<String,Object>>
	 * @Description: 过滤角色的一些属性
	 */
	private List<Map<String, Object>> filterRoleList(List<CboRoleEntity> roleList) {
		List<Map<String, Object>> result = new ArrayList<>();
		if (roleList != null) {
			for (CboRoleEntity cboRoleEntity : roleList) {
				Map<String, Object> role = new HashMap<>();
				role.put("code", cboRoleEntity.getCode());
				role.put("name", cboRoleEntity.getName());
				result.add(role);
			}
		}
		return result;
	}

}
